package com.hellogood.yaohuo.client.common;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.shared.entity.Org;
import com.hellogood.yaohuo.shared.services.OrgService;
import com.smartgwt.client.types.Positioning;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;

public class COrgTextItemTreeClickHandler implements KeyPressHandler {
	private TextItem orgItem = null;
	private TextItem selectItem = null;

	public COrgTextItemTreeClickHandler(TextItem orgItem, TextItem selectItem) {
		this.orgItem = orgItem;
		this.selectItem = selectItem;
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getKeyName().equals("Enter")) {			
			Object org = orgItem.getValue();
			if (org != null && !org.equals("")) {
				if (org.toString().contains("-")) {
					selectItem.focusInItem();
				} else {
					OrgService.Util.getInstance().getCOrgByCode(org.toString(), new AsyncCallback<Org>() {

						@Override
						public void onSuccess(Org result) {
							if (result != null) {
								orgItem.setValue(result.getOrgCode() + "-" + result.getOrgName());
							} else {
								COrgTreeWindow window = new COrgTreeWindow(orgItem, selectItem);
								window.setPosition(Positioning.RELATIVE);
								window.setSize("500", "500");
								window.centerInPage();
								window.setTitle("组织选择");
								window.show();
								window.getTreeGrid().focus();
							}
						}

						@Override
						public void onFailure(Throwable caught) {
							SC.say(caught.getMessage());
						}
					});
				}

			} else {
				COrgTreeWindow window = new COrgTreeWindow(orgItem, selectItem);
				window.setPosition(Positioning.RELATIVE);
				window.focus();
				window.setSize("500", "500");
				window.centerInPage();
				window.setTitle("请选择组织");
				window.show();
				window.getTreeGrid().focus();
			}

		}

	}

}
